﻿using System;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using mojoPortal.Web.RS.SBM.AppCode.Lib;

 
namespace mojoPortal.Web.RS.SBM
{
    public partial class RSManageContact : RSBasePage
    {
        
        int _companyid = 0;
        int _locationid = 0;
        int _contactid = 0;

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
        }
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["contactid"] != null)
                _contactid = Convert.ToInt32(Request.QueryString["contactid"].ToString());
            if (Request.QueryString["locationid"] != null)
                _locationid = Convert.ToInt32(Request.QueryString["locationid"].ToString());

            if (!Page.IsPostBack)
            {
                InitializeReadyServicePage();

                RSUserIdentity userIdentity = GetRSUserIdentity();
                _companyid = userIdentity.RSCompanyId;

                if (_companyid > 0)
                {
                    SetRSPageHeader("Add Contact To Location");
                    //if (Request.QueryString["action"] == "add")
                    //{
                    //    SetRSPageHeader("Add Contact To Location");
                    //    pnlLookupContact.Visible = true;
                    //}
                    //else
                    //{
                    //    SetRSPageHeader("Edit Contact");
                    //    pnlLookupContact.Visible = false;
                    //}
                    if (_locationid > 0)
                    {
                        ucLocationHeaderControl1.LoadLocationHeader(_companyid, _locationid, true);
                        ucLocationHeaderControl2.LoadLocationHeader(_companyid, _locationid, false);
                    }
                    if (_contactid > 0)
                    {
                        PopulateContactData(_contactid, _companyid);
                    }
                }
                if (Request.QueryString["action"] == "add")
                {
                    LoadLookupContact(_companyid);
                    btnDeleteContact.Visible = false;
                }
            }

        }
        protected void btnReturn_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/RS/SBM/RSLocationHistoryContacts.aspx?locationid=" + _locationid);
        }
        protected void btnModalOK_Click(object sender, EventArgs e)
        {
            if (hfRedirectURL.Value.Length > 0)
            {
                //var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
                //nameValues.Set("tabindex", "1");
                //string url = Request.Url.AbsolutePath;
                //string updatedQueryString = "?" + nameValues.ToString();
                //url = url + updatedQueryString;

                //if (url.Contains("RSLocationHistory.aspx"))
                    Response.Redirect("~/RS/SBM/RSLocationHistoryContacts.aspx?locationid=" + ucLocationHeaderControl1.LocationId);
                //else
                    //Response.Redirect(url);
            }
            else
            {
                mpeModalManageContact.Hide();
            }
            
        }
        protected void gvLookupContact_SelectedIndexChanged(Object sender, EventArgs e)
        {
            String contactid = gvLookupContact.SelectedValue.ToString();
            txtContactId.Text = contactid;
            RSUserIdentity userIdentity = GetRSUserIdentity();
            _companyid = userIdentity.RSCompanyId;
            PopulateContactData(Convert.ToInt32(contactid), _companyid);
            mpeModalManageContact.Show();
        }
        protected void btnAddNewContact_Click(object sender, EventArgs e)
        {
            mpeModalManageContact.Show();
        }

        private void PopulateContactData(int contactid, int companyid)
        {
            String strSQL = "select FirstName,MiddleName,LastName,Phone,Mobile,Fax,Email,Title,Note,CompanyId,Active,BillingLocationID from rs_tblContact where contactid=@contactid and companyid=@companyid";
            SqlCommand myCommand;
            SqlParameter param;
            SqlConnection myConnection;
            myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
            myCommand = new SqlCommand(strSQL, myConnection);
            SqlDataReader myDataReader;
            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@contactid";
            param.Value = contactid;
            myCommand.Parameters.Add(param);

            param = null;
            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@companyid";
            param.Value = companyid;
            myCommand.Parameters.Add(param);

            myConnection.Open();
            myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
            if (myDataReader.HasRows)
            {
                myDataReader.Read();
                txtContactId.Text = contactid.ToString();
                txtFirstName.Text = myDataReader["FirstName"].ToString();
                txtMiddleName.Text = myDataReader["MiddleName"].ToString();
                txtLastName.Text = myDataReader["LastName"].ToString();
                txtPhone.Text = myDataReader["Phone"].ToString();
                txtMobile.Text = myDataReader["Mobile"].ToString();
                txtFax.Text = myDataReader["Fax"].ToString();
                txtEmail.Text = myDataReader["Email"].ToString();
                txtTitle.Text = myDataReader["Title"].ToString();
                txtContactNote.Text = myDataReader["Note"].ToString();
                txtBillingLocationId.Text = myDataReader["BillingLocationId"].ToString();
                if(txtBillingLocationId.Text == "0")
                    txtBillingLocationId.Text = "";
            }
            myConnection.Close();
        }
        
        protected void btnClear_Click(object sender, EventArgs e)
        {
            ClearContactDetail();
        }
        private void ClearContactDetail()
        {
            txtContactId.Text = "";
            txtFirstName.Text = "";
            txtMiddleName.Text = "";
            txtLastName.Text = "";
            txtPhone.Text = "";
            txtMobile.Text = "";
            txtFax.Text = "";
            txtEmail.Text = "";
            txtTitle.Text = "";
            txtContactNote.Text = "";
        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite && userIdentity.RSCanDelete)
            {
                _companyid = userIdentity.RSCompanyId;
                _locationid = ucLocationHeaderControl1.LocationId;
                _contactid = txtContactId.Text == "" ? 0 : Convert.ToInt32(txtContactId.Text);

                if (_companyid > 0 && _locationid > 0 && _contactid > 0)
                {
                    SqlCommand sqlCmd = new SqlCommand();
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@locationid", SqlDbType.Int, 0, ParameterDirection.Input, _locationid);
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@contactid", SqlDbType.Int, 0, ParameterDirection.Input, _contactid);
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@companyid", SqlDbType.Int, 0, ParameterDirection.Input, _companyid);
                    SQLHelper.SetCommandType(sqlCmd, CommandType.Text, "DELETE FROM rs_tblContactLocation WHERE ContactId=@contactid AND  LocationId=@locationid AND CompanyId=@companyid; DELETE FROM rs_tblContact WHERE ContactId=@contactid AND CompanyId=@companyid");
                    SQLHelper.ExecuteScalarCmd(sqlCmd);
                    int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
                    lblMessage.Text = "Contact Deleted Successfully!";
                }
            }
            else
                lblMessage.Text = "You Do Not Have Permission To Perform This Action!";

            btnSaveContact.Visible = false;
            btnDeleteContact.Visible = false;
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            int CompanyId = userIdentity.RSCompanyId;
            int LocationId = ucLocationHeaderControl2.LocationId;
            int BillingLocationId = txtBillingLocationId.Text == "" ? 0 : Convert.ToInt32(txtBillingLocationId.Text);
            int ContactId = txtContactId.Text == "" ? 0 : Convert.ToInt32(txtContactId.Text);
            string FirstName = txtFirstName.Text.Trim();
            string MiddleName = txtMiddleName.Text.Trim();
            string LastName = txtLastName.Text.Trim();
            string Phone = txtPhone.Text.Trim();
            string Mobile = txtMobile.Text.Trim();
            string Fax = txtFax.Text.Trim();
            string Email = txtEmail.Text.Trim();
            string Title = txtTitle.Text.Trim();
            string Note = txtContactNote.Text.Trim();

            SqlCommand sqlCmd = new SqlCommand();

            SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@FirstName", SqlDbType.NVarChar, 25, ParameterDirection.Input, FirstName);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@MiddleName", SqlDbType.NVarChar, 25, ParameterDirection.Input, MiddleName);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@LastName", SqlDbType.NVarChar, 25, ParameterDirection.Input, LastName);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@Phone", SqlDbType.NVarChar, 15, ParameterDirection.Input, Phone);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@Mobile", SqlDbType.NVarChar, 15, ParameterDirection.Input, Mobile);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@Fax", SqlDbType.NVarChar, 15, ParameterDirection.Input, Fax);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@Email", SqlDbType.NVarChar, 50, ParameterDirection.Input, Email);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@Title", SqlDbType.NVarChar, 25, ParameterDirection.Input, Title);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@Note", SqlDbType.NVarChar, -1, ParameterDirection.Input, Note);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@Active", SqlDbType.Bit, 0, ParameterDirection.Input, null);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@LocationId", SqlDbType.Int, 0, ParameterDirection.Input, LocationId);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@BillingLocationId", SqlDbType.Int, 0, ParameterDirection.Input, BillingLocationId);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@ContactId", SqlDbType.Int, 0, ParameterDirection.Input, ContactId);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CompanyId", SqlDbType.Int, 0, ParameterDirection.Input, CompanyId);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CurrentUser", SqlDbType.NVarChar, 25, ParameterDirection.Input, userIdentity.RSCurrentUser);
            SQLHelper.SetCommandType(sqlCmd, CommandType.StoredProcedure, "rs_uspSaveContact");
            SQLHelper.ExecuteScalarCmd(sqlCmd);

            int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
            lblMessage.Text = "Contact Successfully Saved!";
            lblMessage.ForeColor = System.Drawing.Color.DarkBlue;
            btnSaveContact.Visible = false;
            btnDeleteContact.Visible = false;
            hfRedirectURL.Value = Request.RawUrl;
            RSSBMCommonFunctions.SetControlsEnabledState(UpdatePanelManageContact.ContentTemplateContainer, false);
        }

        private void LoadLookupContact(int companyid)
        {
            SqlCommand myCommand;
            SqlParameter param;
            SqlConnection myConnection;

            String sqlSELECT =  "SELECT * FROM [rs_tblContact] WHERE CompanyId=@CompanyID ORDER BY LastName, FirstName";

            myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
            myCommand = new SqlCommand(sqlSELECT, myConnection);

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@companyid";
            param.Value = companyid;
            myCommand.Parameters.Add(param);

            SqlDataAdapter adapter = new SqlDataAdapter(myCommand);
            myConnection.Open();
            DataSet ds = new DataSet();
            adapter.Fill(ds);
            Session["DATATABLE"] = ds.Tables[0];
            gvLookupContact.DataSource = ds;
            gvLookupContact.DataBind();
            myConnection.Close();
        }

        private string ConvertSortDirectionToSql(SortDirection sortDirection)
        {
           string newSortDirection = String.Empty;

           switch (sortDirection)
           {
              case SortDirection.Ascending:
                 newSortDirection = "ASC";
                 break;

              case SortDirection.Descending:
                 newSortDirection = "DESC";
                 break;
           }
           return newSortDirection;
        }

        protected void gvLookupContact_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
           gvLookupContact.PageIndex = e.NewPageIndex;
           gvLookupContact.DataBind();
        }

        protected void gvLookupContact_Sorting(object sender, GridViewSortEventArgs e)
        {
           DataTable dataTable = Session["DATATABLE"] as DataTable;
           if (dataTable != null)
           {
              DataView dataView = new DataView(dataTable);
              dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);

              gvLookupContact.DataSource = dataView;
              gvLookupContact.DataBind();
           }
        }
        
    }
}